package com.njit.mailm.core.service.impl;

import com.njit.mailm.commmon.utils.HTMLSpirit;
import com.njit.mailm.core.bean.Email;
import com.njit.mailm.core.bean.MessageWrap;
import com.njit.mailm.core.dao.MailDao;
import com.sun.mail.pop3.POP3Folder;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * Created by Administrator on 2016/5/4.
 */

@Service
public class NewMailServiceImpl extends MailServiceImpl {
    @Autowired
    private MailDao mailDao;
    @Override
    public Map<String, Object> batchSynchron(List<Message> batchList, Email email) {
        return super.batchSynchron(batchList, email);
    }

    @Override
    public MessageWrap packMessage(POP3Folder inbox, Message message, Email email) {
        MessageWrap mWrap = new MessageWrap();
        try {
            mWrap.setId(inbox.getUID(message));
            mWrap.setSubject(message.getSubject());
            mWrap.setFromName(getFrom(message));
            mWrap.setTo(getReceiveAddress(message, Message.RecipientType.TO));
            mWrap.setCopyTo(getReceiveAddress(message, Message.RecipientType.CC));
            mWrap.setBcc(getReceiveAddress(message, Message.RecipientType.BCC));

            mWrap.setTos(getReceiveAddresses(message,Message.RecipientType.TO));
            mWrap.setBccs(getReceiveAddresses(message,Message.RecipientType.BCC));
            mWrap.setCcs(getReceiveAddresses(message,Message.RecipientType.CC));
            StringBuffer content = new StringBuffer();
            getMailTextContent(message, content);
            mWrap.setBody(content.toString());
            String contentprev = HTMLSpirit.delHTMLTag(content.toString());
            if (contentprev.length() > 10) {
                contentprev = contentprev.substring(0, 10) + "...";
            }
            mWrap.setContentPrev(contentprev);
            mWrap.setSendtime(getSentDate(message, "yyyy-MM-dd HH:mm:ss"));
            mWrap.setSize(message.getSize() * 1024 + "kb");

            Address[] froms = message.getFrom();
            if (froms.length < 1)
                throw new MessagingException("没有发件人!");

            InternetAddress address = (InternetAddress) froms[0];
            String from = address.getAddress();
            mWrap.setFrom(from);
            mWrap.setEmail(email);
            return mWrap;
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    protected String[] getReceiveAddresses(Message msg, Message.RecipientType type) throws MessagingException{
        List<String> receiveAddresses = new ArrayList<String>();
        Address[] addresss = null;
        if (type == null) {
            addresss = msg.getAllRecipients();
        } else {
            addresss = msg.getRecipients(type);
        }

        if (addresss == null || addresss.length < 1)
            return null;
        for (Address address : addresss) {
            InternetAddress internetAddress = (InternetAddress)address;
            receiveAddresses.add(internetAddress.toUnicodeString());
        }
        String[] result = new String[receiveAddresses.size()];
        receiveAddresses.toArray(result);
        return  result;
    }

    public Map<String, Object> intervalSynchron(List<Email> emails) {
        Map<String,Object> result = new HashMap<String, Object>();
        result.put("newNumber",0);
        for(Email email:emails){
            Store store = getConnectedStore(email);
            POP3Folder inbox = getInbox(store, email);
            Message[] messages = getMessages(inbox);
            List<MessageWrap> msg = new ArrayList<MessageWrap>();

            try {
                for(int i = messages.length - 1;i>0;i--){
                    String guid = inbox.getUID(messages[i]);
                    MessageWrap mw = mailDao.selectMessageById(guid);
                    if(mw != null){
                        continue;
                    }
                    MessageWrap messageWrap = packMessage(inbox, messages[i], email);
                    super.insertMessage(messageWrap);
                    msg.add(messageWrap);
            }
                if(msg.size()> 0){
                    result.put("newNumber",msg.size());
                    result.put("from",msg.get(0).getFrom());
                    result.put("subject",msg.get(0).getSubject());
                    result.put("id",email.getId());
                }
            } catch (MessagingException e) {
                e.printStackTrace();
            }finally {
                close(inbox,store);
            }
        }

        return result;
    }
}
